using System;
using System.Xml;

namespace stunnware.CRM.Fetch {
   /// <summary>
   /// The FetchOrder class specifies an attribute used to sort a result set.
   /// </summary>
   public class FetchOrder {

      private string _attribute;
      private bool _descending;

      /// <summary>
      /// Default constructor.
      /// </summary>
      public FetchOrder() {
      }

      /// <summary>
      /// Creates a new instance with the default sort order (ascending).
      /// </summary>
      /// <param name="attribute">The attribute name.</param>
      public FetchOrder(string attribute) : this(attribute, false) {
      }

      /// <summary>
      /// Creates a new instance with the specified sort order (ascending).
      /// </summary>
      /// <param name="attribute">The attribute name.</param>
      /// <param name="descending">If true, the result set is sorted descending.</param>
      public FetchOrder(string attribute, bool descending) {
         _attribute = attribute;
         _descending = descending;
      }

      /// <summary>
      /// The attribute name.
      /// </summary>
      public string Attribute {
         get {
            return _attribute;
         }

         set {
            _attribute = value;
         }
      }

      /// <summary>
      /// True, if the sort order is descending.
      /// </summary>
      public bool Descending {
         get {
            return _descending;
         }

         set {
            _descending = value;
         }
      }

      /// <summary>
      /// Adds the definition of this class to an XML document.
      /// </summary>
      /// <param name="entityNode"></param>
      internal void AddToFetchDocument(XmlElement entityNode) {

         XmlElement orderNode = FetchXmlDocument.AddElement(entityNode, "order");
         FetchXmlDocument.AddAttribute(orderNode, "attribute", Attribute);

         if (Descending) {
            FetchXmlDocument.AddAttribute(orderNode, "descending", "true");
         }
      }

      /// <summary>
      /// Parses the passed xml node and creates a new instance from it.
      /// </summary>
      /// <param name="node"></param>
      /// <returns></returns>
      public static FetchOrder FromXml(XmlNode node) {

         XmlAttribute attributeName = node.Attributes["attribute"];
         XmlAttribute descendingNode = node.Attributes["descending"];

         bool descending = (descendingNode == null) ? false : bool.Parse(descendingNode.Value);

         return new FetchOrder(attributeName.Value, descending);
      }
   }
}
